package com.airpi.heavy_tasks;

import java.io.File;

import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.airpi.R;
import com.airpi.activities.MainMiddleFragment;
import com.airpi.connectivity.RaspberryPiDiscoverer;
import com.airpi.connectivity.Streaming;

/**
 * Class that permits to stream the selected file
 *
 */
public class AsyncTaskStreaming extends AsyncTask<Void, Void, String> {

	private FragmentActivity activity;
	private File file;
	private TextView information;
	private MainMiddleFragment fragment;

	public AsyncTaskStreaming(MainMiddleFragment fragment) {
		this.fragment = fragment;
		this.information = fragment.getUploadInformation();
		this.activity = fragment.getActivity();
		this.file = fragment.getFile();
	}

	/**
	 * Send the selected file to the server
	 * @return The server's answer
	 */
	@Override
	protected String doInBackground(Void... arg0) {
		Log.d("debug", "doInBackground method");
		SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(activity); 
		Streaming streaming = new Streaming(activity, file, sharedPrefs.getString(RaspberryPiDiscoverer.PREFS_LAST_FOUND, null));
		streaming.stream();
		return streaming.getResult();
	}



	/**
	 * Inform the user about server's answer
	 */
	@Override
	protected void onPostExecute(String res) {
		if(res != null) {
			if (res.contains("successfully")) {
				information.setTextColor(Color.GREEN);
				information.setText(R.string.file_uploaded);
				fragment.setUploadInformation(information);
			}
			else if (res.contains("error")) {
				information.setTextColor(Color.RED);
				if (res.contains("disconnected")) 
					information.setText(R.string.user_disconnected);
				else
					information.setText(R.string.unknown_error);
				fragment.setUploadInformation(information);
			}
			fragment.setSpinnerUpload(false);
		}
		else
			Toast.makeText(activity, R.string.no_file_selected, Toast.LENGTH_SHORT).show();
	}

}
